﻿using Microsoft.Extensions.Configuration;
using Newtonsoft.Json.Linq;
using Sino.WebApi.Framework.Primitives;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.WebApi
{
    public class ConfigurationOptions
    {

        public Version ApiVersion { get; set; }

        public OsCode Platform { get; set; }

        public string BaseUri { get; set; }

        public string AppId { get; set; }

        public string AppSecrect { get; set; }

        public uint AccessTimeoutRetries { get; set; }

        public int DefaultTimeoutInMillionSeconds { get; set; }

        public JObject ConfigurationRoot { get; set; }

        public string DefaultUserName { get; set; }

        public string DefaultPassword { get; set; }

        public static ConfigurationOptions LoadSettings(string configurationName)
        {
            var assembly = typeof(ConfigurationOptions).GetTypeInfo().Assembly;
            return LoadSettings(assembly, configurationName);
        }

        public static ConfigurationOptions LoadSettings(Assembly assembly, string configurationName)
        {
            var options = new ConfigurationOptions();
            var configurationFileName = $"/WebApiClient.Config.{configurationName}.json";
            try
            {
                var di = new DirectoryInfo(Directory.GetCurrentDirectory());
                string path = di + configurationFileName;
                if (File.Exists(path))
                {
                    FileStream fs = new FileStream(di + configurationFileName, FileMode.Open);
                    using (TextReader reader = new StreamReader(fs))
                    {
                        var jsonString = reader.ReadToEnd();
                        var configurationRoot = JObject.Parse(jsonString);
                        options = configurationRoot.ToObject<ConfigurationOptions>();
                        options.ConfigurationRoot = configurationRoot;
                        return options;
                    }
                }
                throw new FileNotFoundException($"The given configuration file name {configurationFileName} doesn't exist.");
            }
            catch (Exception ex)
            {
                //Mvx.Error($"Failed to load configuration file {configurationFileName}.\r\n{ex.Message}\r\n{ex.StackTrace}");
                throw ex;
            }
        }

    }
}
